<template>
  <div class="add-purchase">
    <div class="add-purchase-btn" @click="handleOpenForm">
      <span>发布采购单</span>
    </div>
    <div v-show="layer !== null" class="add-purchase-form">
      <el-form ref="form" :model="form" :rules="formRules" label-width="110px">
        <p class="form-title">标题</p>
        <el-form-item label="采购单标题" prop="title">
          <el-input v-model="form.title" size="small" placeholder="为该采购单填写标题（必填项）"></el-input>
        </el-form-item>

        <p class="form-title">采购商品计划</p>
        <el-form-item label="商品计划" prop="goods_names">
          <el-radio-group v-model="form.goods_type">
            <el-radio :label="0">现货/标准品</el-radio>
            <el-radio :label="1">加工/订制品</el-radio>
          </el-radio-group>
          <el-table :data="[{}]" border>
            <el-table-column label="商品名称">
              <el-input v-model="form.goods_names"></el-input>
            </el-table-column>
            <el-table-column label="商品分类">
              <el-select v-model="form.goods_category">
                <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-table-column>
            <el-table-column label="数量">
              <el-input-number v-model="form.goods_num" size="small" :controls="false"></el-input-number>
            </el-table-column>
            <el-table-column label="单位">
              <el-input v-model="form.goods_unit" placeholder="件/把/个/瓶..." :minlength="4"></el-input>
            </el-table-column>
            <el-table-column label="规格">
              <el-input v-model="form.goods_sku" placeholder="规格说明"></el-input>
            </el-table-column>
            <el-table-column label="图片/图纸">
              <el-upload multiple
                accept=".jpg,.png" :action="MixinUploadApi" :headers="MixinAccessToken" :on-success="onUploadSuccess" :on-remove="onRemoveImage" :limit="1">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-table-column>
          </el-table>
        </el-form-item>

        <p class="form-title">采购需求</p>
        <el-form-item label="采购截止时间" prop="closing_date">
          <el-date-picker
            v-model="form.closing_date"
            type="date"
            size="small"
            value-format="timestamp"
            :picker-options="{disabledDate(time) { return time.getTime()  <  (Date.now() - 8.64E7)   ||  time.getTime()   > Date.now()  + (8.64E7 * 29) }}"
            placeholder="请选择截止时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="期望收货时间" prop="receiving_date">
          <el-date-picker
            v-model="form.receiving_date"
            type="date"
            size="small"
            value-format="timestamp"
            :picker-options="{disabledDate(time) { return time.getTime()  <  (Date.now() - 8.64E7)   ||  time.getTime()   > Date.now()  + (8.64E7 * 29) }}"
            placeholder="请选择期望收货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="价格说明" prop="goods_price" class="form-item-group">
          <el-radio-group v-model="form.price_type">
            <el-radio :label="0">可议价</el-radio>
            <el-radio :label="1">不可议价</el-radio>
            <el-radio :label="2">面议</el-radio>
          </el-radio-group>
          <div class="form-item-inline goods-price-item">
            <span class="form-item-title">商品单价</span>
            <el-input v-model="form.goods_price" size="small" placeholder="请填写商品单价">
              <template slot="prepend">￥</template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="收货地" prop="ship_county">
          <en-region-cascader
            :province.sync="form.ship_province"
            :city.sync="form.ship_city"
            :county.sync="form.ship_county"
          />
        </el-form-item>
        <el-form-item label="对供应商要求" prop="seller_county" class="form-item-group">
          <div class="form-item-inline">
            <span class="form-item-title">经营地址</span>
            <en-region-cascader
              :province.sync="form.seller_province"
              :city.sync="form.seller_city"
              :county.sync="form.seller_county"
            />
          </div>
          <div class="form-item-inline">
            <span class="form-item-title">发票要求</span>
            <el-radio-group v-model="form.need_receipt">
              <el-radio :label="0">无需发票</el-radio>
              <el-radio :label="1">需要发票</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="补充说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="4" resize="none"/>
        </el-form-item>

        <p class="form-title">询价方式及隐私</p>
        <el-form-item label="联系方式" prop="privacy">
          <el-radio-group v-model="form.privacy">
            <el-radio :label="0">报价后可见</el-radio>
            <el-radio :label="1">公开</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系人" prop="contact_name" class="input-max-width">
          <el-input v-model="form.contact_name" size="small" placeholder="请填写联系人姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_num" class="input-max-width">
          <el-input v-model="form.contact_num" size="small" placeholder="请填写联系电话"></el-input>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import * as API_Purchase from '@/api/purchase'
import { RegExp } from '~/ui-utils'
import {
  Form,
  FormItem,
  Input,
  InputNumber,
  RadioGroup,
  Radio,
  Table,
  TableColumn,
  Select,
  Option,
  Upload,
  DatePicker
} from 'element-ui'

Vue.use(Form)
  .use(FormItem)
  .use(Input)
  .use(InputNumber)
  .use(RadioGroup)
  .use(Radio)
  .use(Table)
  .use(TableColumn)
  .use(Select)
  .use(Option)
  .use(Upload)
  .use(DatePicker)

export default {
  name: 'EnAddPurchase',
  data() {
    return {
      layer: null,
      form: {
        // 标题
        title: '',
        // 商品类型，现货/标准品：0，加工/订制品：1
        goods_type: 0,
        // 商品名称
        goods_names: '',
        // 商品分类
        goods_category: '',
        // 商品数量
        goods_num: 1,
        // 商品单位，件、把、个、瓶
        goods_unit: '',
        // 商品sku
        goods_sku: '',
        // 商品图片
        goods_img: '',
        // 截止时间
        closing_date: '',
        // 期望收货时间
        receiving_date: '',
        // 价格类型，可议价：0，不可议价：1 ，面议：2
        price_type: 0,
        // 商品单价
        goods_price: '',
        // 买家收货地址-省
        ship_province: '',
        // 买家收货地址-市
        ship_city: '',
        // 买家收货地址-县区
        ship_county: '',
        // 要求卖家地址-省
        seller_province: '',
        // 要求卖家地址-市
        seller_city: '',
        // 要求卖家地址-县区
        seller_county: '',
        // 是都需要发票，不需要：0，需要：1
        need_receipt: 0,
        // 联系方式隐私，报价后可见：0，公开：1
        privacy: 0,
        // 联系人姓名
        contact_name: '',
        // 联系人电话
        contact_num: ''
      },
      formRules: {
        title: this.MixinRequired('请填写采购单标题'),
        goods_names: [
          this.MixinRequired('请填写商品名称！'),
          {
            validator: (rule, value, callback) => {
              if (!this.form.goods_category) {
                callback(new Error('请选择商品分类！'))
              } else if (!RegExp.integer.test(this.form.goods_num)) {
                callback(new Error('商品数量填写有误！'))
              } else if (!this.form.goods_unit) {
                callback(new Error('请填写商品单位！'))
              } else {
                callback()
              }
            }
          }
        ],
        closing_date: this.MixinRequired('请选择采购截止时间！'),
        receiving_date: this.MixinRequired('请选择期望收货时间！'),
        goods_price: [
          this.MixinRequired('请填写商品单价！'),
          {
            validator: (rule, value, callback) => {
              if (!RegExp.money.test(value)) {
                callback(new Error('请填写正确的价格！'))
              } else {
                callback()
              }
            }
          }
        ],
        ship_county: this.MixinRequired('请选择收货地址！'),
        seller_county: this.MixinRequired('请选择供应商经营地址！'),
        contact_name: this.MixinRequired('请填写联系人姓名！'),
        contact_num: this.MixinRequired('请填写联系电话！')
      }
    }
  },
  computed: {
    // 商品分类
    categories() {
      let { categories } = this.$store.getters
      return categories.map(item => ({
        label: item.name,
        value: item.category_id
      }))
    }
  },
  methods: {
    /**
     * 打开采购单表单
     */
    handleOpenForm() {
      this.layer = window.layer.open({
        title: '发布采购单',
        type: 1,
        area: ['950px', '1000px'],
        scrollbar: false,
        move: false,
        shade: false,
        zIndex: 188,
        btn: ['确认发布'],
        btnAlign: 'c',
        // eslint-disable-next-line no-undef
        content: $('.add-purchase-form'),
        cancel: this.handleCancel,
        yes: this.handleConfirm
      })
    },
    /**
     * 商品图片上传成功
     * @param response
     * @param file
     */
    onUploadSuccess(response, file) {
      this.form.goods_img = response.name
    },
    /**
     * 移除商品图片
     */
    onRemoveImage() {
      this.form.goods_img = ''
    },
    /**
     * 取消填写表单
     * @param index
     * @returns {boolean}
     */
    handleCancel(index) {
      window.layer.confirm('表单尚未保存，确定要关闭吗？', {
        icon: 3,
        title: '提示',
        area: ['275px'],
        closeBtn: 0,
        scrollbar: false,
        move: false
      }, function(c_index) {
        window.layer.close(c_index)
        window.layer.close(index)
        this.layer = null
      })
      return false
    },
    /**
     * 确认发布
     * @param index
     */
    handleConfirm(index) {
      const params = JSON.parse(JSON.stringify(this.form))
      params.closing_date /= 1000
      params.receiving_date /= 1000
      this.$refs['form'].validate(async(valid) => {
        if (!valid) {
          this.$message.error('表单填写有误，请核对！')
          return false
        }
        await API_Purchase.addPurchase(params)
        this.$alert('发布成功！', () => {
          window.layer.close(index)
          this.layer = null
        })
      })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.add-purchase {
  .add-purchase-btn {
    position: fixed;
    top: 50%;
    right: 0;
    z-index: 999;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100px;
    height: 50px;
    color: #ffffff;
    font-weight: bold;
    font-size: 16px;
    background-color: #405db1;
    cursor: pointer;
    box-shadow: 0 0 10px 0 #cccccc;
    border-radius: 5px 0 0 5px;
    transition: all .2s ease;
    &:hover {
      background-color: #3c5194;
    }
  }
  .add-purchase-form {
    width: 100%;
    height: 100%;
    padding: 15px 30px;
    box-sizing: border-box;
    /*background-color: #F2F2F2;*/
    /deep/ {
      table {
        thead th {
          padding: 0;
          text-align: center;
        }
        .cell {
          text-overflow: initial;
          text-align: center;
        }
        .el-input__inner {
          height: 30px;
          line-height: 30px;
        }
        .el-input-number {
          width: 95px;
        }
        .el-select__caret {
          line-height: 30px;
        }
      }
      .form-title {
        position: relative;
        line-height: 40px;
        font-size: 14px;
        padding-left: 15px;
        border-bottom: 1px dashed #c0c4cc;
        margin-bottom: 10px;
        &::before {
          content: ' ';
          position: absolute;
          left: 0;
          top: 50%;
          margin-top: -9px;
          width: 4px;
          height: 18px;
          background-color: #164FB3;
          border-radius: 2px;
        }
      }
      .form-item-group {
        .form-item-title {
          margin-right: 10px;
        }
        .el-form-item__content {
          margin-left: 100px;
          border: 1px dashed #c0c4cc;
          padding: 10px;
          border-radius: 5px;
        }
      }
      .input-max-width {
        .el-input {
          width: 220px;
        }
      }
      .form-item-inline {
        display: flex;
        align-items: center;
      }
      .goods-price-item {
        width: 300px;
        .el-input {
          width: 180px;
        }
      }
    }
  }
}
</style>
